<template>
  <div>
    <el-dialog
      :visible.sync="userSettingVisible"
      title="修改用户信息"
      width="50%"
      @close="closeDialog"
    >
      <el-form :model="editList" :rules="formRules" ref="settingForm">
        <el-form-item label="用户名">
          <el-input v-model="editList.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editList.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editList.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="settingUser(editList)"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex'
export default {
  name: 'EditDialog',
  data() {
    const emailzz = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
    const numberzz =
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    const checkEmail = (rule, value, cb) => {
      if (value === '') return cb(new Error('邮箱不能为空!'))
      if (emailzz.test(value)) {
        cb()
      } else {
        cb(new Error('邮箱格式不正确!'))
      }
    }
    const checkNumber = (rule, value, cb) => {
      if (value === '') return cb(new Error('手机号码不能为空!'))
      if (numberzz.test(value)) {
        cb()
      } else {
        cb(new Error('号码格式不正确!'))
      }
    }
    return {
      formRules: {
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' },
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    userSettingVisible: {
      get() {
        return this.$store.state.user.userSettingVisible
      },
      set() {
        this.$store.commit('user/closeDialog', false)
      }
    },
    ...mapState('user', {
      editList: 'editList'
    })
  },
  methods: {
    closeDialog() {
      this.$store.commit('user/closeDialog', false, 'user')
      this.$refs.settingForm.resetFields()
      this.$store.commit('user/editData', {}, 'user')
    },
    // 修改用户数据
    settingUser(data) {
      this.$refs.settingForm.validate(async (valid) => {
        if (!valid) return this.$message.error('修改的数据格式不正确!')

        const { data: res } = await this.$http.put(`users/${data.id}`, {
          email: data.email,
          mobile: data.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败!')
        this.$message.success('修改成功!')
        this.closeDialog()
        this.$emit('updateList')
      })
    }
  }
}
</script>

<style></style>
